import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import github from 'next-auth/providers/github';
import { authConfig } from './config';
import bcrypt from 'bcrypt';
import { getUser } from '../db/data';
// import { z } from 'zod'; // zod：用于验证输入输出的库

export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
  providers: [
    github,
    Credentials({
      name: 'credentials',
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials, req) {
        if (typeof credentials !== "undefined") {
          // const parsedCredentials = z
          //   .object({ email: z.string().email(), password: z.string().min(6) })
          //   .safeParse(credentials);
          const user = await getUser(credentials.email as string);
          if (!user) return null;

          const passwordsMatch = await bcrypt.compare(credentials.password as string, user.password);
          if (passwordsMatch) return user;
        }
        return null
      }
    }),
  ],
});
